package ua.kpi.ipsa.expert.api.client;

import java.awt.event.*;
import java.io.*;
import java.rmi.*;
import java.util.*;

import javax.swing.*;

import net.miginfocom.swing.*;
import ua.kpi.ipsa.expert.api.net.*;

/**
 * 
 * @author doctorpro
 * 
 */
public class CodePortionUploader extends JPanel {

	private ClientFrameManager cfm;
	private JFrame parent;
	private JFrame frame;
	private JTextField pathField;
	private JTextField nameField;
	private JTextField voozField;
	private JTextField groupField;
	private JTextField etcField;
	private File mainFile = null;

	private ActionListener closeHandler;

	private List<SourceFile> sourceFiles = new ArrayList<SourceFile>();

	/**
	 * Create the panel.
	 */
	public CodePortionUploader(ClientFrameManager cfm, JFrame parent,
			ActionListener closeHandler) {
		this.cfm = cfm;
		this.parent = parent;
		this.closeHandler = closeHandler;
		setLayout(new MigLayout("", "[][grow][]", "[][][][][][grow][]"));

		JLabel lblPath = new JLabel("path:");
		add(lblPath, "cell 0 0,alignx trailing");

		pathField = new JTextField();
		pathField.setEnabled(false);
		add(pathField, "cell 1 0,growx");
		pathField.setColumns(10);

		JButton btnBrowse = new JButton("Browse");
		btnBrowse.addActionListener(new BrowseHandler());
		add(btnBrowse, "cell 2 0");

		JLabel lblName = new JLabel("name:");
		add(lblName, "cell 0 1,alignx trailing");

		nameField = new JTextField();
		add(nameField, "cell 1 1 2 1,growx");
		nameField.setColumns(10);

		JLabel lblGroup = new JLabel("vooz:");
		add(lblGroup, "cell 0 2,alignx trailing");

		voozField = new JTextField();
		add(voozField, "cell 1 2 2 1,growx");
		voozField.setColumns(10);

		JLabel lblNewLabel = new JLabel("group:");
		add(lblNewLabel, "cell 0 3,alignx right");

		groupField = new JTextField();
		add(groupField, "cell 1 3 2 1,growx");
		groupField.setColumns(10);

		JLabel lblEtc = new JLabel("etc:");
		add(lblEtc, "cell 0 4,alignx trailing");

		etcField = new JTextField();
		add(etcField, "cell 1 4 2 1,growx,aligny top");
		etcField.setColumns(10);

		JPanel panel = new JPanel();
		add(panel, "cell 0 6 3 1,grow");
		panel.setLayout(new MigLayout("", "[][grow][]", "[23px]"));

		JButton btnBack = new JButton("Back");
		btnBack.addActionListener(new BackHandler());
		panel.add(btnBack, "cell 0 0,alignx left,aligny top");

		JButton btnUpload = new JButton("Upload");
		btnUpload.addActionListener(new UploadHandler());
		panel.add(btnUpload, "cell 2 0");

		frame = cfm.createFrame();
		frame.setContentPane(this);
		frame.setTitle("Upload code portion");
		frame.pack();
		frame.setLocationByPlatform(true);
		frame.addWindowListener(new CloseHandler());
		frame.setVisible(true);
	}

	/**
	 * 
	 */
	private void showDialog() {
		JFileChooser c = new JFileChooser();
		c.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		int r = c.showOpenDialog(frame);
		if (r == JFileChooser.APPROVE_OPTION) {
			mainFile = c.getSelectedFile();

			try {
				pathField.setText(mainFile.getCanonicalPath());
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {

		}
	}

	/**
	 * 
	 * @param f
	 */
	private void addFile(File f) {
		if (f.isFile()) {
			SourceFile sf = new SourceFile();
			sf.path = getFilePath(f);
			sf.body = readFile(f);
			sourceFiles.add(sf);
		} else if (f.isDirectory()) {
			File[] files = f.listFiles();
			for (int i = 0; i < files.length; i++) {
				addFile(files[i]);
			}
		}
	}

	/**
	 * 
	 * @param f
	 * @return
	 */
	private String readFile(File f) {
		FileReader fr = null;
		BufferedReader br = null;
		StringBuilder sb = null;
		try {
			sb = new StringBuilder();
			fr = new FileReader(f);
			br = new BufferedReader(fr);
			String line;
			while ((line = br.readLine()) != null)
				sb.append(line + "\n"); // We use \n as a line separator.
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (br != null)
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (fr != null)
				try {
					fr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}

		return sb.toString();
	}

	/**
	 * 
	 * @param f
	 * @return
	 */
	private String[] getFilePath(File f) {
		ArrayList<String> result = new ArrayList<String>();

		while (f != null) {
			result.add(f.getName());
			f = f.getParentFile();
		}

		String[] result2 = new String[result.size()];
		for (int i = 0; i < result2.length; i++) {
			result2[result2.length - 1 - i] = result.get(i);
		}

		return result2;
	}

	/**
	 * 
	 */
	private void onBack() {
		cfm.disposeFrame(frame);
		closeHandler.actionPerformed(null);
		parent.setVisible(true);
	}

	/**
	 * 
	 * @author doctorpro
	 * 
	 */
	private class BrowseHandler implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			showDialog();
		}
	}

	/**
	 * 
	 * @author doctorpro
	 * 
	 */
	private class UploadHandler implements ActionListener {

		/**
		 * 
		 */
		@Override
		public void actionPerformed(ActionEvent e) {
			String result = checkInfo();
			if (result.equals("")) {
				//
				UsersConsole c = cfm.getConsole();
				sourceFiles.clear();
				addFile(mainFile);
				try {
					c.postCodePortion(nameField.getText(),
							groupField.getText(), voozField.getText(),
							etcField.getText(), sourceFiles);
					System.out.println("cp posted");
				} catch (RemoteException | ConsoleException e1) {
					JOptionPane.showMessageDialog(null, "Internal error");
					cfm.ceaseOperations();
					e1.printStackTrace();
				}

			} else {
				JOptionPane.showMessageDialog(null, "Errors in input:\n"
						+ result);
			}
		}

		/**
		 * 
		 * @return
		 */
		private String checkInfo() {
			String result = "";

			if (!checkName(nameField.getText())) {
				result = assertSeparator(result) + "Illegal name.";
			}
			if (pathField.getText().equals("")) {
				result = assertSeparator(result) + "Empty path.";
			}

			return result;
		}

		/**
		 * 
		 * @param s
		 * @return
		 */
		private boolean checkName(String s) {

			for (int i = 0; i < s.length(); i++) {
				if (!Character.isLetter(s.charAt(i)) && (s.charAt(i) != ' ')) {
					return false;
				}
			}
			return true;
		}

		/**
		 * 
		 * @param s
		 * @return
		 */
		private String assertSeparator(String s) {
			if (s.equals("")) {
				return s;
			} else {
				return s + "\n";
			}
		}
	}

	/**
	 * 
	 * @author doctorpro
	 * 
	 */
	private class BackHandler implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			onBack();
		}
	}

	/**
	 * 
	 * @author doctorpro
	 * 
	 */
	private class CloseHandler extends WindowAdapter {

		@Override
		public void windowClosing(WindowEvent e) {
			onBack();
		}
	}

	protected JTextField getPathField() {
		return pathField;
	}
}
